# -*- coding: utf-8 -*-

from flask import Flask, render_template, request, jsonify
from movement import MovementMode
import threading
from web_remote import *
from config import ServoConfig
from servo import Servo

app = Flask(__name__)

# 模式切换事件
mode_changed = threading.Event()

# 舵机初始化角度事件
servo_config_changed = threading.Event()

# 路由用于显示 index.html 页面
@app.route('/webctrl/')
def webctrl():
    return render_template('index.html')

# 路由用于显示 servo-setting.html 页面
@app.route('/servo-setting')
def servo_setting():
    return render_template('servo-setting.html')

# 设定mode API
@app.route('/api/remote/<mode>')
def remote_control(mode):
    input_mode = MovementMode.get_value(mode)
    inner_mode = getCurrentMode()
    if inner_mode == input_mode:
        return mode
    
    setCurrentMode(input_mode)
    print(f"Received mode: {mode}, value: {input_mode}")

    # 设置mode changed事件通知运动子线程
    if not mode_changed.is_set():
        mode_changed.set()
    return mode

# 获取当前mode API
@app.route('/api/remote/getmode')
def remote_status():
    inner_mode = getCurrentMode()
    return MovementMode.get_label(inner_mode)

# 设定当前servo offset
@app.route('/api/remote/set-servo-offset', methods=['POST'])
def set_servo_offset():
    offset = request.get_json()
    ServoConfig.setOffset(offset)
    servo_config_changed.set()
    
    remote_control(MovementMode.get_label(MovementMode.MOVEMENT_FORWARD.value))
    sleep(1)
    remote_control(MovementMode.get_label(MovementMode.MOVEMENT_STANDBY.value))

    return jsonify({ }), 200

# 获取当前servo offset
@app.route('/api/remote/get-servo-offset')
def get_servo_offset():
    return jsonify(ServoConfig.getOffset()), 200

# 设置某关节角度
@app.route('/api/remote/set-servo-angle', methods=['POST'])
def set_servo_angle():
    params = request.get_json()
    if 'leg' not in params or 'part' not in params or 'angle' not in params:
        return jsonify({ "error": "wrong params" }), 500
    
    leg = params['leg']
    part = params['part']
    angle = params['angle']
    servo = Servo()
    servo.set_angle(leg, part, angle)
    return jsonify({ "error": "ok" }), 200

if __name__ == '__main__':
    # 初始化舵机事件
    servo_config_changed.clear()

    # 开启movement线程
    mode_changed.set()
    moving_thread = threading.Thread(target=web_moving_thread, args=(mode_changed, servo_config_changed),
                                      daemon=True)
    moving_thread.start()

    # 开启HTTP服务
    app.run(debug=False, host='0.0.0.0', port=8080)